﻿using UnityEngine;

namespace UFrame
{
    public class CameraFollow : MonoBehaviour
    {
        public Transform player;
        public Vector3 offsetStation;
        [Range(0, 10)] public float speedRate = 1f;

        public bool isStartOffset = true;
        [Header("必须大于当前目标"), Range(0, 2f)] public float ignoreDistance = 0.3f;

        void Awake()
        {
            //transform.LookAt(player.position);
            if (isStartOffset)
            {
                CalOffset();
            }
        }

        public void SetTarget(Transform player)
        {
            this.player = player;
            CalOffset();
        }


        public void CalOffset()
        {
            if (isStartOffset && player != null)
            {
                offsetStation = transform.position - player.position;
            }
        }

        private void Update()
        {
            if (player == null)
                return;

            //第一种方式
            Vector3 current = transform.position - offsetStation;
            Vector3 toward = player.position - current;
            Vector3 v = Vector3.Lerp(current, player.position, speedRate * Time.deltaTime);
            var dis = Vector3.Distance(current, player.position);
            if (dis < ignoreDistance)
            {
                return;
            }

            transform.position = v + offsetStation;
        }
    }
}